﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

using RemoteScriptingLibrary.Microsoft.Win32;


namespace RemoteScriptingLibrary
{
    public class HookWrapper : IDisposable
    {   
        public delegate void TextEventHandler(object sender, TextEventArgs e);
        public static IntPtr _hookID = IntPtr.Zero;
        private static Win32.LowLevelKeyboardProc _proc = HookCallback;

        public event TextEventHandler m_TextEventHandler = null;

        private static HookWrapper m_HookWrapper = null;

        public HookWrapper()
        {
            m_HookWrapper = this;
            _hookID = SetHook(_proc);
            _proc = HookCallback;
        }

        
        /// <summary>
        /// Set Hook
        /// </summary>
        /// <param name="proc"></param>
        /// <returns></returns>
        private static IntPtr SetHook(Win32.LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return Win32.SetWindowsHookEx(Win32.WH_KEYBOARD_LL, proc,
                    Win32.GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        protected virtual void OnTextReceived(TextEventArgs e)
        {
            if (m_TextEventHandler != null)
            {
                m_TextEventHandler(this, e);
            }
        }

        /// <summary>
        /// Hook Callback
        /// </summary>
        /// <param name="nCode"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)Win32.WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                Keys key = (Keys)vkCode;
                m_HookWrapper.OnTextReceived(new TextEventArgs(key.ToString()));
                Console.WriteLine(key);
            }
            return Win32.CallNextHookEx(_hookID, nCode, wParam, lParam);
        }
     
        public void Dispose()
        {
            Win32.UnhookWindowsHookEx(_hookID); IntPtr ptr2 = Helper.GetDacWindow();
        }
    }
}
